package com.dmwork.service.interaction.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmwork.common.base.result.R;
import com.dmwork.common.base.util.JwtInfo;
import com.dmwork.common.base.util.JwtUtils;
import com.dmwork.service.interaction.entity.WorkComment;
import com.dmwork.service.interaction.entity.WorkCommentLike;
import com.dmwork.service.interaction.entity.vo.WorkCommentVo;
import com.dmwork.service.interaction.feign.CustomerFeignService;
import com.dmwork.service.interaction.service.WorkCommentLikeService;
import com.dmwork.service.interaction.service.WorkCommentService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Transactional
@Api(description = "全局作品评论管理")
@RestController
@RequestMapping("/front/dm_work/interaction/work_comment")
public class FrontWorkCommentController {

    @Autowired
    private WorkCommentService workCommentService;
    @Autowired
    private WorkCommentLikeService workCommentLikeService;
    @Autowired
    private CustomerFeignService customerFeignService;

    @ApiOperation("通过评论id获取指定评论详情")
    @GetMapping("get_comment/{commentId}")
    public R getComment(HttpServletRequest request, @ApiParam("评论id") @PathVariable("commentId") String commentId) {
        WorkComment workComment = workCommentService.getById(commentId);
        WorkCommentVo workCommentVo = new WorkCommentVo();
        //转换Emoji
        if (!StringUtils.isEmpty(workComment.getContent())) {
            workComment.setContent(EmojiParser.parseToUnicode(workComment.getContent()));
        }
        BeanUtils.copyProperties(workComment, workCommentVo);
        //获取评论所属用户的用户名与头像
        R result = customerFeignService.getBaseInfo(workComment.getCustomerId());
        if (!result.getSuccess()) {
            return R.error().message("获取失败");
        }
        workCommentVo.setCustomerName((String) result.getData().get("customerName"));
        workCommentVo.setAvatar((String) result.getData().get("avatar"));
        //如果该评论是条回复，获取被回复用户的用户名
        if (workComment.getRepliedCommentId() != null) {
            R res = customerFeignService.getBaseInfo(workComment.getRepliedCustomerId());
            if (!res.getSuccess()) {
                return R.error().message("获取失败");
            }
            workCommentVo.setRepliedCustomerName((String) res.getData().get("customerName"));
        }
        //判断当前用户是否有点赞该评论
        checkCommentIsLikedAndOwn(request, workCommentVo, workComment.getId(), workComment.getCustomerId());
        return R.ok().data("data", workCommentVo);
    }

    @ApiOperation("获取的是当前作品详情下的所有对作品的评论")
    @GetMapping("get_comment_list/{workId}/{sortType}/{page}/{limit}")
    public R getCommentList(HttpServletRequest request, @ApiParam("评论的作品id") @PathVariable String workId, @ApiParam("评论排序规则") @PathVariable Integer sortType, @ApiParam("页数") @PathVariable Integer page, @ApiParam("每页记录数") @PathVariable Integer limit) {
        Page<WorkComment> workCommentPage = workCommentService.getCommentPage(workId, sortType, page, limit);
        if (workCommentPage.getRecords().isEmpty()) {
            return R.ok().message("暂无评论");
        }
        //获取每条评论的用户名和头像
        List<String> customerIdList = new ArrayList<>();
        for (WorkComment workComment : workCommentPage.getRecords()) {
            customerIdList.add(workComment.getCustomerId());
        }
        R result = customerFeignService.getBriefInfoList(customerIdList);
        if (!result.getSuccess()) {
            return R.error().message("获取失败");
        }
        Map<String, Object> resultData = (Map<String, Object>) result.getData().get("result");
        List<WorkCommentVo> workCommentVoList = new ArrayList<>();
        for (WorkComment workComment : workCommentPage.getRecords()) {
            WorkCommentVo workCommentVo = new WorkCommentVo();
            //转换Emoji
            if (!StringUtils.isEmpty(workComment.getContent())) {
                workComment.setContent(EmojiParser.parseToUnicode(workComment.getContent()));
            }
            BeanUtils.copyProperties(workComment, workCommentVo);
            ArrayList<String> info = (ArrayList<String>) resultData.get(workComment.getCustomerId());
            workCommentVo.setCustomerName(info.get(0));
            workCommentVo.setAvatar(info.get(1));
            //判断当前用户是否有点赞该评论
            checkCommentIsLikedAndOwn(request, workCommentVo, workComment.getId(), workComment.getCustomerId());
            //查询当前的作品评论下有多少条回复
            int count = workCommentService.count(new QueryWrapper<WorkComment>().eq("parent_comment_id", workComment.getId()));
            workCommentVo.setReplyCount(count);
            workCommentVoList.add(workCommentVo);
        }

        return R.ok().data("total", workCommentPage.getTotal()).data("rows", workCommentVoList);
    }

    @ApiOperation("获取指定的作品评论下的多条回复评论")
    @GetMapping("get_reply_list/{commentId}/{sortType}/{page}/{limit}")
    public R getReplyList(HttpServletRequest request, @PathVariable String commentId, @PathVariable Integer sortType, @PathVariable Integer page, @PathVariable Integer limit) {

        Page<WorkComment> workCommentPage = workCommentService.getReplyPage(commentId, sortType, page, limit);
        if (workCommentPage.getTotal() == 0) {
            return R.ok().message("暂无回复").data("total", 0);
        }
        //获取每条评论的所属用户的用户名和头像，若该评论所回复的评论也是一条回复，则获取该评论所属用户的用户名
        List<String> customerIdList = new ArrayList<>(); //评论所属用户id
        List<String> repliedCustomerIdList = new ArrayList<>(); //被回复者用户id
        for (WorkComment workComment : workCommentPage.getRecords()) {
            customerIdList.add(workComment.getCustomerId());
            //RepliedCommentId和ParentCommentId相等，说明是直接回复作品评论，否则是对评论下其它回复的一条回复
            if (!workComment.getRepliedCommentId().equals(workComment.getParentCommentId())) {
                repliedCustomerIdList.add(workComment.getRepliedCustomerId());
            }
        }
        R customerResult = customerFeignService.getBriefInfoList(customerIdList); //获取评论所属用户信息
        R repliedCustomerResult = null;
        if (!repliedCustomerIdList.isEmpty()) { //获取被回复者用户信息
            repliedCustomerResult = customerFeignService.getBriefInfoList(repliedCustomerIdList);
            if (!customerResult.getSuccess() || !repliedCustomerResult.getSuccess()) {
                return R.error().message("获取失败");
            }
        }

        Map<String, Object> customerResultData = (Map<String, Object>) customerResult.getData().get("result");
        Map<String, Object> repliedCustomerResultData = null;
        if (repliedCustomerResult != null) {
            repliedCustomerResultData = (Map<String, Object>) repliedCustomerResult.getData().get("result");
        }
        List<WorkCommentVo> workCommentVoList = new ArrayList<>();
        for (WorkComment workComment : workCommentPage.getRecords()) { //组装数据，填写对应的用户名和头像数据
            WorkCommentVo workCommentVo = new WorkCommentVo();
            //转换Emoji
            if (!StringUtils.isEmpty(workComment.getContent())) {
                workComment.setContent(EmojiParser.parseToUnicode(workComment.getContent()));
            }
            BeanUtils.copyProperties(workComment, workCommentVo);
            ArrayList<String> customerInfoList = (ArrayList<String>) customerResultData.get(workComment.getCustomerId());
            workCommentVo.setCustomerName(customerInfoList.get(0)); //获取用户名
            workCommentVo.setAvatar(customerInfoList.get(1)); //获取头像
            if (repliedCustomerResultData != null && !workComment.getRepliedCommentId().equals(workComment.getParentCommentId())) {
                ArrayList<String> repliedCustomerInfoList = (ArrayList<String>) repliedCustomerResultData.get(workComment.getRepliedCustomerId());
                workCommentVo.setRepliedCustomerName(repliedCustomerInfoList.get(0)); //获取用户名
            }
            //判断当前用户是否有点赞该评论
            checkCommentIsLikedAndOwn(request, workCommentVo, workComment.getId(), workComment.getCustomerId());
            workCommentVoList.add(workCommentVo);
        }
        return R.ok().data("total", workCommentPage.getTotal()).data("rows", workCommentVoList);
    }

    @ApiOperation("获取当前作品的评论总数")
    @GetMapping("get_work_comment_count/{workId}")
    public R getWorkCommentCount(@ApiParam("作品id") @PathVariable String workId) {
        QueryWrapper<WorkComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_id", workId);
        int count = workCommentService.count(queryWrapper);
        return R.ok().data("count", count);
    }


    /////////////////////////////   私有方法   ///////////////////////////////

    /**
     * 判断当前用户是否有点赞该评论以及是否是自己的评论
     *
     * @param request       请求
     * @param workCommentVo
     * @param commentId     评论id
     */
    private void checkCommentIsLikedAndOwn(HttpServletRequest request, WorkCommentVo workCommentVo, String commentId, String customerId) {
        //判断当前用户是否有点赞该评论
        try {
            JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
            int count = workCommentLikeService.count(new QueryWrapper<WorkCommentLike>().eq("customer_id", jwtInfo.getId()).eq("comment_id", commentId));
            if (count > 0) {
                workCommentVo.setLiked(true); //若有点赞数据，则设置为true，否则为false
            } else {
                workCommentVo.setLiked(false);
            }
            if (customerId.equals(jwtInfo.getId())) {
                workCommentVo.setOwn(true);
            } else {
                workCommentVo.setOwn(false);
            }
        } catch (Exception e) { //若未登录，则直接为false
            workCommentVo.setLiked(false);
            workCommentVo.setOwn(false);
        }
    }

}
